﻿using LeEdu.DAL;
using LeEdu.MODEL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeEdu.BLL;
using System.IO;
namespace LeEdu.Web.Controllers
{
    public class OrderController : Controller
    {
        OrderBLL obl = new OrderBLL();
        /// <summary>
        /// Create Sunshine 3:24
        /// </summary>
        //
        // GET: /Order/
        //实例化上下文类
        DbContextEntity entity = new DbContextEntity();
       
        /// <summary>
        /// 课程订单管理
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult CourseOrder(string keyword, int id = 1)
        {
            ViewBag.guan = keyword;
            string aa = ViewBag.guan;
            ViewBag.pageindex = id;
            List<Order> showcourseorder = entity.Order.Where(p => (p.Otype == "课程") && (string.IsNullOrEmpty(aa) ? true : p.Oname.Contains(aa))).ToList();
            double count = showcourseorder.Count;
            double pagecount = Math.Ceiling(count / 10);
            ViewBag.pagecount = pagecount;
            List<Order> show = showcourseorder.OrderByDescending(p => p.OcreateDate).Skip((id - 1) * 10).Take(10).ToList();
            return View(show);
        }
        /// <summary>
        /// 班级订单
        /// </summary>
        /// <returns></returns>
        public ActionResult ClassOrder(string keyword, int id = 1)
        {
            ViewBag.guan = keyword;
            string aa = ViewBag.guan;
            ViewBag.pageindex = id;
            List<Order> showcourseorder = entity.Order.Where(p => (p.Otype == "班级") && (string.IsNullOrEmpty(aa) ? true : p.Oname.Contains(aa))).ToList();
            double count = showcourseorder.Count;
            double pagecount = Math.Ceiling(count / 10);
            ViewBag.pagecount = pagecount;
            List<Order> show = showcourseorder.OrderByDescending(p => p.OcreateDate).Skip((id - 1) * 10).Take(10).ToList();
            return View(show);

        }
        /// <summary>
        /// 虚拟币订单
        /// </summary>
        /// <returns></returns>
        public ActionResult VirtualOrder(string keyword, int id = 1)
        {
            ViewBag.guan = keyword;
            string aa = ViewBag.guan;
            ViewBag.pageindex = id;
            List<Order> showcourseorder = entity.Order.Where(p => (p.Otype == "虚拟币") && (string.IsNullOrEmpty(aa) ? true : p.Oname.Contains(aa))).ToList();
            double count = showcourseorder.Count;
            double pagecount = Math.Ceiling(count / 10);
            ViewBag.pagecount = pagecount;
            List<Order> show = showcourseorder.OrderByDescending(p => p.OcreateDate).Skip((id - 1) * 10).Take(10).ToList();
            return View(show);
        }
        /// <summary>
        /// 订单详情查看
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult CourseOrderXQ(int id)
        {
            return View(entity.Order.Where(p => p.OID == id).FirstOrDefault());
        }
        //点击购买课程生成订单（未支付）
        public ActionResult purchase(int id,string name, string Otype, string Onum, decimal? Oprice)
        {
           CourseBLL coursebll = new CourseBLL();
           ViewBag.list = coursebll.getEntityList(p => true).Where(p => p.CoursesId == id).ToList();
            //实例化BLL
            OrderBLL obl = new OrderBLL();
            if (Session["Uname"] == null)
            {
                return Content("<script>alert('您好！请登录！');location.href='/Login/Index';</script>");
            }
            else if (Otype == "班级")
            {

                ClassTableBLL cl = new ClassTableBLL();

                //班级的查找
                ClassTable grade = cl.Search(id);
                
                Random rd1 = new Random();
                if (Onum == null || Onum == "")
                {
                    //商户订单号
                    string bh = "BJ" + DateTime.Now.ToString("yyyyMMddhhmmss") + rd1.Next(10000, 99999);
                    //支付宝交易号
                    string jyh = "";
                    //交易状态
                    string jyzt = "未付款";

                    Order dd = new Order();
                    dd.Oname = grade.CTName;
                    dd.Oprice = grade.CTPrice;
                    dd.OpayDate = "";
                    dd.Omoney = Convert.ToDecimal(Oprice);
                    dd.OcreateDate = DateTime.Now.ToString("yyyy-MM-dd");
                    dd.Otype = Otype;
                    dd.Onum = bh;
                    dd.OtradeNum = jyh;
                    dd.OtradeState = jyzt;
                    dd.UserID = Convert.ToInt32(Session["id"]);
                    dd.CourseID = id;
                    

                    obl.AddEntity(dd);
                    ViewBag.bh = bh;
                    ViewBag.Price = dd.Oprice;
                    ViewBag.Otype = Otype;
                    return View("purchase");
                }
            }
            else if (Otype == "课程")
            {
                CourseBLL col = new CourseBLL();
                Courses cour = col.Search(id);
                Random rd = new Random();
                if (Onum == null || Onum == "")
                {

                    //商户订单号
                    string bh = "KC" + DateTime.Now.ToString("yyyyMMddhhmmss") + rd.Next(10000, 99999);
                    //支付宝交易号
                    string jyh = "";
                    //交易状态
                    string jyzt = "未付款";

                    Order dd = new Order();
                    dd.Oname = cour.CoursesName;
                    dd.Oprice = Convert.ToDecimal(cour.CPrice);
                    dd.OpayDate = "";
                    dd.Omoney = Convert.ToDecimal(Oprice);
                    dd.OcreateDate = DateTime.Now.ToString("yyyy-MM-dd");
                    dd.Otype = Otype;
                    dd.Onum = bh;
                    dd.OtradeNum = jyh;
                    dd.OtradeState = jyzt;
                    dd.UserID = Convert.ToInt32(Session["id"]);
                    dd.CourseID = id;

                    obl.AddEntity(dd);
                    ViewBag.bh = bh;
                    ViewBag.Price = dd.Oprice;
                    ViewBag.Otype = Otype;
                    return View("purchase");
                }


            }
            else if (Otype == "充值")
            {

                Random rd = new Random();
                if (Onum == null || Onum == "")
                {
                    //商户订单号
                    string bh = "CZ" + DateTime.Now.ToString("yyyyMMddhhmmss") + rd.Next(100, 999) + Session["id"];

                    //支付宝交易号
                    string jyh = "";
                    //交易状态
                    string jyzt = "未付款";

                    Order dd = new Order();
                    dd.Oname = "账户充值";
                    dd.Oprice = Convert.ToDecimal(Oprice);
                    dd.OpayDate = "";
                    dd.Omoney = Convert.ToDecimal(Oprice);
                    dd.OcreateDate = DateTime.Now.ToString("yyyy-MM-dd");
                    dd.Otype = Otype;
                    dd.Onum = bh;
                    dd.OtradeNum = jyh;
                    dd.OtradeState = jyzt;
                    dd.UserID = Convert.ToInt32(Session["id"]);
                    dd.CourseID = id;

                    obl.AddEntity(dd);
                    ViewBag.bh = bh;
                    ViewBag.Price = dd.Oprice;
                    ViewBag.Otype = Otype;


                    return View("purchase");



                }


            }
            else if (Otype == "" || Otype == null)
            {
                //商户订单号
                string bh = Onum;
                
                ViewBag.bh = bh;
                ViewBag.Price = Oprice;
                return View("purchase");
            }
            return View("purchase");
        }
        //支付宝返回结果
        public ActionResult notify()
        {
            OrderBLL obl = new OrderBLL();

            //商户订单号
            string bh = Request.QueryString["out_trade_no"];
            //支付宝交易号
            string Djyh = Request.QueryString["trade_no"];
            //交易状态
            string jyzt = Request.QueryString["trade_status"];

            string ss = bh.Substring(0, 2);
            int jj = Convert.ToInt32(bh.Remove(0, 19));
            //'该判断表示买家已在支付宝交易管理中产生了交易记录，但没有付款

            //    '判断该笔订单是否在商户网站中已经做过处理
            //        '如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
            //            '请务必判断请求时的price、quantity、seller_id与通知时获取的price、quantity、seller_id为一致的
            //        '如果有做过处理，不执行商户的业务程序


            if (Request.QueryString["trade_status"] == "WAIT_BUYER_PAY")
            {

                Order order = obl.getEntity(t => t.Onum == bh);
                order.OtradeNum = Djyh;
                order.OtradeState = "未付款";
                obl.Edit(order);



            }




            //'该判断表示买家已在支付宝交易管理中产生了交易记录且付款成功，但卖家没有发货

            //    '判断该笔订单是否在商户网站中已经做过处理
            //        '如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
            //            '请务必判断请求时的price、quantity、seller_id与通知时获取的price、quantity、seller_id为一致的
            //        '如果有做过处理，不执行商户的业务程序

            else if (Request.QueryString["trade_status"] == "WAIT_SELLER_SEND_GOODS")
            {
                Order order = obl.getEntity(t => t.Onum == bh);
                order.OtradeNum = Djyh;
                order.OtradeState = "等待卖家发货";
                obl.Edit(order);

                if (ss == "CZ")
                {
                    DbContextEntity db = new DbContextEntity();

                    BllTable btable = db.BllTable.Where(t => t.UserInfoId == jj).OrderByDescending(t => t.ID).FirstOrDefault();

                    BllTable bbb = new BllTable();
                    if (btable != null)
                    {
                        bbb.B_Balance = btable.B_Balance + Convert.ToDecimal(Request.QueryString["price"]);
                    }
                    else
                    {

                        bbb.B_Balance = 0;
                    }

                    bbb.B_Name = "充值";
                    bbb.B_Num = bh;
                    bbb.B_Money = Convert.ToDecimal(Request.QueryString["price"]);
                    bbb.B_Type = "现金";
                    bbb.B_Date = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                    bbb.UserInfoId = jj;

                    BllTableBLL ball = new BllTableBLL();
                    ball.AddEntity(bbb);
                }



            }

             //'该判断表示卖家已经发了货，但买家还没有做确认收货的操作

             //    '判断该笔订单是否在商户网站中已经做过处理
            //        '如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
            //            '请务必判断请求时的price、quantity、seller_id与通知时获取的price、quantity、seller_id为一致的
            //        '如果有做过处理，不执行商户的业务程序

            else if (Request.QueryString["trade_status"] == "WAIT_BUYER_CONFIRM_GOODS")
            {
                Order order = obl.getEntity(t => t.Onum == bh);
                order.OtradeNum = Djyh;
                order.OtradeState = "确认收货";
                obl.Edit(order);


            }


             //'该判断表示买家已经确认收货，这笔交易完成

             //    '判断该笔订单是否在商户网站中已经做过处理
            //        '如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
            //            '请务必判断请求时的price、quantity、seller_id与通知时获取的price、quantity、seller_id为一致的
            //        '如果有做过处理，不执行商户的业务程序

            else if (Request.QueryString["trade_status"] == "TRADE_FINISHED")
            {
                Order order = obl.getEntity(t => t.Onum == bh);
                order.OtradeNum = Djyh;
                order.OtradeState = "交易完成";
                obl.Edit(order);

            }

            else
            {
                Order order = obl.getEntity(t => t.Onum == bh);
                order.OtradeNum = Djyh;
                order.OtradeState = "交易失败";
                obl.Edit(order);

            }

            ////跳转页面显示订单信息
            //Common.SQLBase sb = new Common.SQLBase();
            //DDXX list = sb.GetListModel<DDXX>("DDXX", "", "Dbh ='" + bh + "'").FirstOrDefault();
            //ViewBag.DDXX = list;
            return Content("<script>alert('" + ss + "');location.href='/Order/MyOrder/" + jj + "';</script>");



        }

        //我的订单页面
        public ActionResult MyOrder( int PageIndex = 1)
        {
            int id = Convert.ToInt32(Session["id"]);
            OrderBLL bll = new OrderBLL();
            int PageSize = 5;
            int pageCount = 0;
            int total = 0;
            var list = bll.getEntityPagging(t => t.OID, t => t.UserID == id, PageIndex, PageSize, out total, out pageCount);
            ViewBag.PageIndex = PageIndex;
            ViewBag.PageCount = pageCount;
            ViewBag.PageSize = PageSize;
            ViewBag.list = list;
            BllTableBLL btable = new BllTableBLL();
            BllTable btab = btable.getEntityList(t => t.UserInfoId == id).OrderByDescending(t => t.ID).FirstOrDefault();
            decimal? Yue = btab == null ? 0 : btab.B_Balance;
            ViewBag.Yue = Yue;

            return View();
        }
        //已经付款的
        public ActionResult MyFukuan(int id, int PageIndex = 1)
        {
            OrderBLL bll = new OrderBLL();
            int PageSize = 5;
            int pageCount = 0;
            int total = 0;
            var list = bll.getEntityPagging(t => t.OID, t => t.UserID == id, PageIndex, PageSize, out total, out pageCount).Where(t => t.OtradeState == "等待卖家发货");
            ViewBag.PageIndex = PageIndex;
            ViewBag.PageCount = pageCount;
            ViewBag.PageSize = PageSize;

            string data = "";
            foreach (var item in list)
            {
                data += "<tr><td>" + item.Oname + "</td><td></td><td>" + item.OtradeState + "</td><td><span>" + item.Oprice + "</span></td>";
                if (item.OtradeState == "等待卖家发货")
                {
                    data += "<td><div class='btn-group'><a class='btn btn-default btn-sm' href='#'>管理</a><a href='/Admin/' type='button' class='btn btn-default btn-sm dropdown-toggle' data-toggle='dropdown'> <span class='caret'></span> </a><ul class='dropdown-menu pull-right'><li> <a class='recommend-course' data-toggle='modal' href='/Order/purchase?id=@item.CourseID&Onum=@item.Onum&Oprice=@item.Oprice'><span class='glyphicon glyphicon-hand-up'></span>我要退货</a></li><li class='divider'></li><li><a class='close-course' href='/Home/cancelOrder/" + item.OID + "' onclick='return confirm('确认删除吗？')'><span class='glyphicon glyphicon-ban-circle'></span> 删除订单</a></li></ul> </div> </td>";
                }
            }
            return Content(data);
        }

        /// <summary>
        /// 现金账单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="PageIndex"></param>
        /// <returns></returns>
        public ActionResult Cash(int id, int PageIndex = 1)
        {
            OrderBLL bll = new OrderBLL();
            int PageSize = 5;
            int pageCount = 0;
            int total = 0;
            var list = bll.getEntityPagging(t => t.OID, t => t.UserID == id, PageIndex, PageSize, out total, out pageCount);
            ViewBag.PageIndex = PageIndex;
            ViewBag.PageCount = pageCount;
            ViewBag.PageSize = PageSize;
            ViewBag.list = list;
            return View();

        }
        /// <summary>
        /// 乐币
        /// </summary>
        /// <returns></returns>
        public ActionResult LeBi(int id)
        {
            BllTableBLL btable = new BllTableBLL();
            BllTable btab = btable.getEntityList(t => t.UserInfoId == id).OrderByDescending(t => t.ID).FirstOrDefault();
            decimal? Yue = btab == null ? 0 : btab.B_Balance;
            ViewBag.Yue = Yue;

            return View();
        }
        /// <summary>
        /// 取消订单
        /// </summary>
        /// <returns></returns>
        public ActionResult cancelOrder(int id)
        {
            Order order = obl.Search(id);
            obl.Del(order);
            return RedirectToAction("/MyOrder/" + Session["id"]);
        }

        /// <summary>
        /// 退货
        /// </summary>
        /// <param name="Onum"></param>
        /// <returns></returns>
        public ActionResult returnedgoods(Refund ss)
        {
            if (ss.Treason == null || ss.Treason == "")
            {
                return Content("2");
            }
            else 
            {
                RefundBLL rbll = new RefundBLL();
                ss.Date = DateTime.Now;
                if (rbll.AddEntity(ss))
                {
                    int OID =Convert.ToInt32(ss.OID);
                    Order order = obl.getEntity(t => t.OID == OID);
                    order.OtradeState = "退货审核中！！";
                    obl.Edit(order);
                    return Content("1");
                }
                else
                {
                    return Content("0");
                }
            }


        }
        /// <summary>
        /// 退货模态框
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Tmotai(string id)
        {
            Order tuihuo = obl.getEntity(t => t.Onum == id);
            ViewBag.tuihuo = tuihuo;
            return View();
        }

        /// <summary>
        /// 批量导出需要导出的列表
        /// </summary>
        /// <returns></returns>
        public FileResult ExportStu2()
        {
            OrderBLL bll = new OrderBLL();
            //获取list数据
            var checkList = bll.GetAll().ToList();

            //创建Excel文件的对象
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");

            //貌似这里可以设置各种样式字体颜色背景等，但是不是很方便，这里就不设置了

            //给sheet1添加第一行的头部标题
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("编号");
            row1.CreateCell(1).SetCellValue("姓名");
            row1.CreateCell(1).SetCellValue("性别");
            row1.CreateCell(1).SetCellValue("住址");
            row1.CreateCell(1).SetCellValue("学校");
            row1.CreateCell(1).SetCellValue("联系电话");
            //....N行

            //将数据逐步写入sheet1各个行
            for (int i = 0; i < checkList.Count; i++)
            {
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                rowtemp.CreateCell(0).SetCellValue(checkList[i].Onum.ToString());
                rowtemp.CreateCell(1).SetCellValue(checkList[i].Oname.ToString());
                rowtemp.CreateCell(2).SetCellValue(checkList[i].OpayDate.ToString());
                rowtemp.CreateCell(3).SetCellValue(checkList[i].Oprice.ToString());
                rowtemp.CreateCell(4).SetCellValue(checkList[i].Ovirtual.ToString());
                rowtemp.CreateCell(5).SetCellValue(checkList[i].Omoney.ToString());
                //....N行
            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            DateTime dt = DateTime.Now;
            string dateTime = dt.ToString("yyMMddHHmmssfff");
            string fileName = "查询结果" + dateTime + ".xls";
            return File(ms, "applicationnd.ms-excel", fileName);
        }
    

    }
}
